import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../../shared/service/login.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  phone: number;
  password: any;
  name: string;

  loading: Boolean = false;
  error: String = '';

  user: object = {};

  constructor(
    private router: Router,
    private loginService: LoginService
  ) {

  }

  ngOnInit() {
    // this.checkPhone('186111');
  }

  back() {
    this.router.navigateByUrl('/login');
  }

  // 教研手机
  checkPhone(phone) {
    let bool = false;
    if (phone.match(/(^13[0-9])|(^15[0-9])|(^17[0-9])|(^18[0-9])[0-9]\d{8}$/) !== null) {
      bool = true;
    }
    return bool
  }

  /*****
  *  注册方法
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  Register() {

    if (!this.phone || !this.password || !this.name) {
      return false;
    }

    if (this.checkPhone(this.phone)) {
      return false;
    }

    const param = {
      phone: this.phone,
      password: this.password,
      name: this.name,
      date: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDay()
    };

    // 设置按钮 loading
    this.loading = true;

    this.loginService.register(param)
        .then((res) => {
          this.loading = false;
          // 接收返回的状态码 400 200
          if (res['state'] === 200) {
            this.error = '注册成功';
            this.user = res['data'];
            this.router.navigateByUrl('/login');
          }
          if (res['state'] === 400) {
            this.error = res['error'];
          }
        });
  }


}
